package com.example.lib_base.widget

import android.graphics.Canvas
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Region
import android.os.Build
import androidx.recyclerview.widget.RecyclerView

/**
 * RecycleView圆角
 *
 *  RecyclerViewCornerRadius radiusItemDecoration = new RecyclerViewCornerRadius(mRecyclerView);
        radiusItemDecoration.setCornerRadius(DisplayUtil.dip2px(mContext, 8));
        mRecyclerView.addItemDecoration(radiusItemDecoration);
 */
class RecycleViewCornerRadius constructor(val recyclerView: RecyclerView) :
    RecyclerView.ItemDecoration() {

    private var rectF: RectF? = null
    private var path: Path? = null
    private var topLeftRadius = 0f
    private var topRightRadius = 0f
    private var bottomLeftRadius = 0f
    private var bottomRightRadius = 0f

    init {
        recyclerView.viewTreeObserver.addOnGlobalLayoutListener {
            rectF = RectF(
                0f,
                0f,
                recyclerView.measuredWidth.toFloat(),
                recyclerView.measuredHeight.toFloat()
            )
            path = Path()
            path?.let {
                it.reset()
                it.addRoundRect(
                    rectF!!, floatArrayOf(
                        topLeftRadius, topLeftRadius,
                        topRightRadius, topRightRadius,
                        bottomLeftRadius, bottomLeftRadius,
                        bottomRightRadius, bottomRightRadius
                    ),Path.Direction.CCW
                )
            }
        }
    }

    fun setCornerRadius(radius: Float){
        this.topLeftRadius = radius
        this.topRightRadius = radius
        this.bottomLeftRadius = radius
        this.bottomRightRadius = radius
    }

    fun setCornerRadius(topLeftRadius:Float,topRightRadius:Float,bottomLeftRadius:Float,bottomRightRadius:Float){
        this.topLeftRadius = topLeftRadius
        this.topRightRadius = topRightRadius
        this.bottomLeftRadius = bottomLeftRadius
        this.bottomRightRadius = bottomRightRadius
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
//        super.onDraw(c, parent, state)
        c.clipRect(rectF!!)
        if (Build.VERSION.SDK_INT >= 28){
            c.clipPath(path!!)
        }else{
            c.clipPath(path!!,Region.Op.REPLACE)
        }
    }


}